<?php

namespace App\Http\Service\Admin;

use Common\Repository\AdminRepository;
use Common\Repository\AdminRolesRepository;
use Illuminate\Support\Facades\Hash;

class AdminService
{
    /**
     * 获取列表
     *
     * @param array $get_data
     * @return array
     */
    public function getList($get_data = [])
    {
        try {
            if(isset($get_data['where']['roles'])){
                $arr_option['whereHas'] = (int)$get_data['where']['roles'];
                unset($get_data['where']['roles']);
            }
            if (isset($get_data['field']) && isset($get_data['order'])) {
                $arr_option['order'] = ['key' => $get_data['field'], 'value' => $get_data['order']];
            }
            $arr_option['field'] = ['id', 'name', 'phone', 'email', 'status', 'created_at'];
            $arr_option['limit'] = $get_data['limit'];
            $arr_option['where'] = $get_data['where'];
            $arr_option['with'] = ['admin_roles'];

            $result = AdminRepository::extendGetList($arr_option);

            foreach ($result['data'] as $key => &$value) {
                if ($value['admin_roles']) {
                    $roles_array = array_column($value['admin_roles'], 'display');
                    $value['admin_roles'] = implode('，', $roles_array);
                }
            }

            $list = list_data_page($result);

            return $list;
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 角色
     *
     * @return false|string
     */
    public function getRoles()
    {
        $roles = RolesService::getAll();
        $data = [];
        foreach ($roles['data'] as $key => $item) {
            $data[] = [
                'id' => $item['id'],
                'name' => $item['display']
            ];
        }

        return json_encode($data);
    }

    /**
     * 添加操作
     *
     * @param array $post_data
     * @param string $roles
     * @return array
     */
    public function insert($post_data = [], $roles = '')
    {
        try {
            //密码加密
            $post_data['password'] = Hash::make($post_data['password']);

            $result = AdminRepository::addOne($post_data);

            $role = self::insertRoles($result['id'], $roles);

            if ($result && $role['code'] == 0) {
                return hello_success('添加成功！', $result);
            }

            return hello_error('添加失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 添加管理员角色
     *
     * @param $admin_id
     * @param string $roles
     * @return array
     */
    public function insertRoles($admin_id, $roles = '')
    {
        $role_arr = explode(',', $roles['roles']);
        if ($admin_id && $role_arr) {

            AdminRolesRepository::deleteByWhere(['admin_id' => $admin_id], true);

            $data = [];
            foreach ($role_arr as $item) {
                $data[] = [
                    'admin_id' => $admin_id,
                    'roles_id' => $item
                ];
            }
            $result = AdminRolesRepository::addMany($data);

            if ($result) {
                return hello_success('添加成功！');
            }
        }
        return hello_error('添加失败！');
    }

    /**
     * 编辑视图
     *
     * @param int $id
     * @return array
     */
    public function edit(int $id)
    {
        try {
            if ($id == 0) {
                //error_prompt('参数错误');
                $id = admin_info()['id'];
            }

            $arr_option['with'] = ['admin_roles'];
            $result = AdminRepository::findOne($id, $arr_option);
            $result['password'] = substr($result['password'], 0, 6);

            $roles_array = [];//管理员角色数组
            if ($result['admin_roles']) {
                $roles_array = array_column($result['admin_roles'], 'id');
            }

            $result['admin_roles'] = json_encode($roles_array);

            if ($result) {
                return hello_success('获取成功！', $result);
            }

            return hello_error('获取失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 编辑操作
     *
     * @param array $post_data
     * @param string $roles
     * @return array
     */
    public function update($post_data = [], $roles = '')
    {
        try {
            $result = AdminRepository::findOne($post_data['id']);
            $password_old = substr($result['password'], 0, 6);
            if ($password_old != $post_data['password']) {
                //密码加密
                $post_data['password'] = Hash::make($post_data['password']);
            } else {
                unset($post_data['password']);
            }

            $result = AdminRepository::editOne($post_data);

            $role = self::insertRoles($post_data['id'], $roles);

            if ($result && $role['code'] == 0) {
                return hello_success('编辑成功！', $result);
            }

            return hello_error('编辑失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 删除操作
     *
     * @param int $id
     * @return array
     */
    public function delete(int $id)
    {
        try {
            if ($id == 0) {
                error_prompt('参数错误');
            }
            $result = AdminRepository::deleteOne($id);

            if ($result) {
                return hello_success('删除成功！', $result);
            }

            return hello_error('删除失败失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 修改密码操作
     *
     * @param array $post_data
     * @return array
     */
    public function updatePassword($post_data = [])
    {
        try {
            // 对比两次输入
            if ($post_data['password'] != $post_data['repassword']) {
                return hello_error('两次输入不一致！');
            }

            $admin = admin_info();
            $old = AdminRepository::findOne($admin['id']);
            // 对比原密码
            if (!Hash::check($post_data['oldPassword'], $old['password'])) {
                return hello_error('原密码不正确！');
            }

            $up_password = [
                'id' => $admin['id'],
                'password' => Hash::make($post_data['password'])
            ];

            $result = AdminRepository::editOne($up_password);

            if ($result) {
                return hello_success('修改成功！', $result);
            }

            return hello_error('修改失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**修改状态
     *
     * @param array $post_data
     * @return array
     */
    public function editStatus($post_data = [])
    {
        try {
            $up_status = [
                'id' => $post_data['id'],
                'status' => $post_data['status'] == 1 ? 0 : 1
            ];

            $result = AdminRepository::editOne($up_status);

            if ($result) {
                return hello_success('修改成功！', $up_status['status']);
            }

            return hello_error('修改失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }
}